<template>
  <el-container style="background-color: #e9ffff">
    <el-aside width="10%"/>
    <el-main class="myloginmain">
      <el-row style="height:20%"/>
      <el-row style="height:60%">
        <el-col :span="10"/>
        <el-col :span="14">
          <el-row style="height:20%"></el-row>
          <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" label-width="80px">
            <el-row style="justify-content: center;"><h1>登录或注册</h1></el-row>
            <el-form-item label="用户名" prop="username">
              <el-input placeholder="请输入用户名" v-model="loginForm.username"/>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input placeholder="请输入密码" v-model="loginForm.password" show-password/>
            </el-form-item>
            <el-form-item style="display: flex;justify-content: center;">
              <el-button :loading="loading" type="primary" @click="login" @keyup.enter="login"
                         style="width: 120px;">
                登录
              </el-button>
              <el-button :loading="loading" type="primary" @click="registerAndLogin" @keyup.enter="registerAndLogin"
                         style="width: 120px;">
                注册并登录
              </el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <el-row style="height:20%"/>


    </el-main>
    <el-aside width="10%"/>
  </el-container>
</template>

<script setup lang="ts">
let loginFormRef = ref<FormInstance>();
let loading = ref(false);
let loginForm = ref({
  username: '',
  password: ''
})

let checkUsername = (rule: any, value: any, callback: any) => {
  if (!value || value.trim() === '') {
    callback(new Error('请输入用户名'));
  } else {
    let p = /^[a-zA-Z0-9_-]{3,18}$/;
    if (p.test(value)) {
      callback();
    } else {
      callback(new Error('用户名不合法,数字、字母、_、-,3到18位'));
    }
  }
}

let loginRules = computed(() => {
  return {
    username: [
      {required: true, message: '请输入用户名', trigger: 'blur'},
      {validator: checkUsername, trigger: 'blur'},

    ],
    password: [
      {required: true, message: '请输入密码', trigger: 'blur'},
      {min: 6, max: 36, message: '长度6到36', trigger: 'blur'},

    ]
  }
})

let userLoginData = computed(() => {
  return {
    username: loginForm.value.username,
    password: rsacoder.encrypt(loginForm.value.password),
    device: "PC"
  }
})

async function login() {
  loginFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      loading.value = true;
      userapi.loginByUsername(userLoginData.value)
          .then((data) => {
            setToken(data.token);
            router.push({path: "/"});
          })
          .catch(async (e) => {
            if (e.message == "1") {
              ElMessageBox.confirm(
                  `<div style="display: flex;flex-direction: column;align-items: center;">
<span style="color: #0077ff">是否使用刚才填写的立即注册一个账号?</span>
<div> <span style="color: red">用户名: <span style="color: black;font-weight: bold">${userLoginData.value.username}</span></span>
<span style="color: red">密码: <span style="color: black;font-weight: bold">${loginForm.value.password}</span></span> </div> </div>`,
                  '注册',
                  {
                    dangerouslyUseHTMLString: true,
                    confirmButtonText: '注册并登录',
                    cancelButtonText: '已有账号，不注册',
                    type: 'info',
                  }
              )
                  .then(async () => {
                    await userapi.registerAndLogin(userLoginData.value).then((data) => {
                      setToken(data.token);
                      router.push({path: "/"});
                    })
                  })
            }
          })
          .finally(() => {
            loading.value = false;
          });
    }
  });
}


async function registerAndLogin() {
  loginFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      loading.value = true;
      userapi.registerAndLogin(userLoginData.value)
          .then((data) => {
            setToken(data.token);
            router.push({path: "/"});
          })
          .finally(() => {
            loading.value = false;
          });
    }
  });
}

</script>

<style scoped>
.myloginmain {
  border-radius: 3px;
  background-image: url("@/assets/login.png");
  background-size: cover;
  max-width: 100%;
  max-height: 100%;
}

.myloginmain::-webkit-scrollbar {
  display: none;
}

</style>
